var conclusion = '所选时间区间内，累计保养[total]次。<br>' +
    '            定保次数[dingbao]次，一级保养[primary]次，二级保养[secondary]次，故障维修[preventive]次，预防性维修[troubleshooting]次。<br>' +
    '            <span id="gzwx">其中[device1]设备故障维修次数最多，达到[max]次，设备故障次数偏多可能会影响企业安全生产和生产效益，请着重关注。</span><br>' +
    '           <span id="yfxwx"> [device2]设备预防性维修次数最多，设备老化可能导致预防性维修次数过多，从而影响生产效率，请着重关注。</span>';
var titleTo = ['#', '设备名称', '设备编号', '使用率', '维保种类', '计划时间', '完成时间', '实施用时', '维保内容', '更换材料清单', '实施人', '检查验证人'];
var labelTo = ['order', 'name', 'sn', 'usageRate', 'species', 'planningTime', 'maintenanceTime', 'timeCost', 'content', 'materialList', 'implementer', 'checkVerifier'];
var pageSize = 5;
$(function () {
    //触发...的tooltip
    chart_pie.setOption(option_pie);
    chart_bar.setOption(option_bar);
    loadData();
});

function loadData() {
    showLoading("加载中");
    getDateRangeMaintenance();
    getFailureRanking();
    loadMaintenanceData();
}

$('#page').paging({
    pageNo: 0,
    totalPage: 0,
    totalSize: 0
});
var date_eg = laydate.render({
    elem: '#searchTimeBegin',
    range: '~',
    change: function (value, date, endDate) {
        if (!isNull(value)) {
            var strings = value.split(" ~ ");
            if (oneMonthLimit(strings[0], strings[1])) {
                date_eg.hint("请将时间范围控制在30天内");
            }
        }
    }
});
var chart_pie = echarts.init(document.getElementById('chart_pie'));
var chart_bar = echarts.init(document.getElementById('chart_bar'));
var option_pie = {//保养情况分布
    color: ['#F8DD83', '#718BF3', '#FF7931', '#5DDF91', '#0096FF'],
    legend: {
        orient: 'vertical',
        right: 16,
        top: 'middle',
        icon: 'rect',
        itemHeight: 16,
        itemWidth: 16,
        itemGap: 16,
        textStyle: {
            color: '#83D0EF',
            fontSize: 16,
            padding: [0, 5]
        }
    },
    tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)',
        backgroundColor: 'rgba(39, 71, 105, 0.7)'
    },
    series: [{
        name: '次数',
        type: 'pie',
        radius: [62, 86],
        center: [187, '50%'],
        label: {
            formatter: '{b}\n{c}次',
            color: '#fff',
            lineHeight: 16
        },
        labelLine: {
            length: 16,
            length2: 0
        },
        data: [
            {value: 0, name: '定保次数'},
            {value: 0, name: '一级保养'},
            {value: 0, name: '二级保养'},
            {value: 0, name: '预防性维修'},
            {value: 0, name: '故障维修'}
        ]
    }]
};
var option_bar = { //维保用时分析
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow',
            shadowStyle: {
                color: 'rgba(59, 85, 159, 0.3)'
            }
        },
        backgroundColor: 'rgba(39, 71, 105, 0.7)'
    },
    grid: {
        top: 30,
        left: 0,
        right: 0,
        bottom: 0,
        containLabel: true
    },
    xAxis: {
        data: ['1小时以内', '1-3小时', '3-5小时', '大于5小时'],
        type: 'category',
        axisLine: {
            lineStyle: {
                color: 'rgba(209, 230, 249, 0.7)'
            }
        },
        axisLabel: {
            color: 'rgba(209, 230, 249, 0.7)'
        },
        axisTick: {
            lineStyle: {
                color: 'rgba(209, 230, 249, 0.7)'
            }
        },
        splitLine: {
            show: false
        }
    },
    yAxis: {
        type: 'value',
        name: '台',
        nameTextStyle: {
            color: '#fff'
        },
        axisLine: {
            show: false
        },
        axisLabel: {
            color: '#fff'
        },
        axisTick: {
            show: false
        },
        splitLine: {
            lineStyle: {
                color: ['rgba(22, 126, 226, 0.2)'],
                type: 'dashed'
            }
        }
    },
    series: [{
        name: '设备数量',
        type: 'bar',
        data: [0, 0, 0, 0],
        barMaxWidth: 38,
        label: {
            show: true,
            position: 'top',
            color: '#FAD488',
            formatter: '{c}台',
            fontSize: 14,
            distance: 11
        },
        itemStyle: {
            color: new echarts.graphic.LinearGradient(
                0, 0, 0, 1,
                [
                    {offset: 0, color: '#00E3D2'},
                    {offset: 1, color: 'rgba(0,0,0,0)'}
                ]
            )
        },
    }]
};

function getDateRangeMaintenance() {
    getJson("/maintenance/getDateRangeMaintenance", {dateTime: $('#searchTimeBegin').val()}, 'GET', function (data) {
        var dingbao = Number(0);
        var primary = Number(0);
        var secondary = Number(0);
        var preventive = Number(0);
        var troubleshooting = Number(0);


        var hour1 = Number(0);
        var hours1to3 = Number(0);
        var hours3to5 = Number(0);
        var MoreThan5Hours = Number(0);
        data.map(function (item) {
            switch (item['species']) {
                case 1:
                    dingbao++;
                    break;
                case 2:
                    primary++;
                    break;
                case 3:
                    secondary++;
                    break;
                case 4:
                    preventive++;
                    break;
                case 5:
                    troubleshooting++;
                    break;
            }
            if (Number(item['timeCost']) < 1) {
                hour1++;
            }
            if (Number(item['timeCost']) >= 1 && Number(item['timeCost']) <= 3) {
                hours1to3++;
            }
            if (Number(item['timeCost']) > 3 && Number(item['timeCost']) <= 5) {
                hours3to5++;
            }
            if (Number(item['timeCost']) > 5) {
                MoreThan5Hours++;
            }
        });
        chart_bar.setOption({
            series: [{
                data: [hour1, hours1to3, hours3to5, MoreThan5Hours],
            }]
        });
        chart_pie.setOption({
            series: [{
                data: [
                    {value: dingbao, name: '定保次数'},
                    {value: primary, name: '一级保养'},
                    {value: secondary, name: '二级保养'},
                    {value: preventive, name: '预防性维修'},
                    {value: troubleshooting, name: '故障维修'}
                ]
            }]
        });
        var total = dingbao + primary + secondary + preventive + troubleshooting;
        $('#ljby').text(total);
        getJson("/maintenance/getConclusion/", {dateTime: $('#searchTimeBegin').val()}, 'GET', function (data) {
            var cl = conclusion.replace('[total]', total)
                .replace('[dingbao]', dingbao).replace('[primary]', primary).replace('[secondary]', secondary)
                .replace('[preventive]', troubleshooting)
                .replace('[troubleshooting]', preventive).replace("[device1]", data['payload']['device1']).replace("[max]", data['payload']['max']).replace("[device2]", data['payload']['device2']);
            $('#conclusion').html(cl);
            if (isNull(data['payload']['device1'])) {
                $('#gzwx').remove();
            }
            if (isNull(data['payload']['device2'])) {
                $('#yfxwx').remove();
            }

            hideLoading();
        });
    })
}

function getFailureRanking() {
    getJson("/maintenance/getFailureRanking", {dateTime: $('#searchTimeBegin').val()}, 'GET', function (data) {
        $('#table_id').empty();
        var tr;
        var paihang = 1;
        var quantity = 0;
        if (data[0]) {
            quantity = isNull(data[0]['quantity']) ? 0 : data[0]['quantity'];
        }
        for (var i = 0; i < 5; i++) {
            if (i > 0) {
                if ((data[i] && data[i - 1]) && (data[i]['quantity'] != data[i - 1]['quantity'])) {
                    paihang += 1;
                }
            }
            if (data[i] && data[i]['device']) {
                tr += ' <tr class="paihang' + paihang + '">' +
                    '<td>' + data[i]['device']['name'] + '</td>' +
                    '<td><i class="iconfont icon-lujing55' + paihang + '"></i></td>' +
                    '<td class="w-100">' +
                    '<div class="progress">' +
                    '<div class="progress-bar" style="width: ' + data[i]['quantity'] / quantity * 100 + '%"></div>' +
                    '</div>' +
                    '</td>' +
                    '<td class="font-p12">' + data[i]['quantity'] + '次</td>' +
                    '</tr>';
            }
        }
        $('#table_id').append(tr);
    })
}

function loadMaintenanceData(_pageIndex) {
    showLoading(LOADING);
    var pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage = pageIndex;
    getJson("/maintenance/getInfoList", {
        dateTime: $('#searchTimeBegin').val(),
        pageIndex: pageIndex,
        pageSize: pageSize
    }, 'GET', function (result) {
        if (result['code'] == 200) {
            var data = result['payload']['data'];
            $("#page").paging({
                pageNo: pageIndex,
                totalPage: result.payload.pages,
                totalSize: result.payload.total,
                showJump: true,
                callback: function (num) {
                    loadMaintenanceData(num);
                },
                showSizeChange: true,
                sizeList: [5, 10, 15, 20],
                pageSize: pageSize,
                sizeChangeFun: function (size) {
                    pageSize = size;
                    loadMaintenanceData(1);
                }
            });
            var order = 1 + pageSize * (pageIndex - 1);
            data.map(function (item) {
                item['order'] = order++;
            });
            buildTable($('#export_table'), titleTo, labelTo, data, function (td, label, item) {
                switch (label) {
                    case "usageRate":
                        $(td).empty();
                        $(td).text(Math.round(item['usageRate'] * 100) / 100 + '%');
                        break;
                    case "content":
                        $(td).empty();
                        var div = createElement("div", $(td), item['content'], null);
                        $(div).addClass('text-truncate').addClass('more-tooltip');
                        $(div).attr('data-toggle', 'tooltip');
                        $(div).attr('title', "");
                        $(div).attr('data-original-title', item['content']);
                        break;
                    case "materialList":
                        $(td).empty();
                        var divMaterialList = createElement("div", $(td), item['materialList'], null);
                        $(divMaterialList).addClass('text-truncate').addClass('more-tooltip');
                        $(divMaterialList).attr('data-toggle', 'tooltip');
                        $(divMaterialList).attr('data-original-title', item['materialList']);
                        break;
                    case "planningTime":
                        $(td).empty();
                        if (item['species'] == 1) {
                            var lastMaintenance = parseInt(item['lastMaintenanceTime']);
                            var cycle = parseInt(item['maintenanceCycle']);
                            /*下次维保时间*/
                            var nextMaintenance = lastMaintenance + parseInt(cycle * 24 * 60 * 60 * 1000);
                            $(td).text(getDate(nextMaintenance).date());
                        }
                        break;
                    case "species":
                        $(td).empty();
                        var tem = '';
                        switch (item['species']) {
                            case 1:
                                tem = '定保';
                                break;
                            case 2:
                                tem = '一级保养';
                                break;
                            case 3:
                                tem = '二级保养';
                                break;
                            case 4:
                                tem = '预防性维修';
                                break;
                            case 5:
                                tem = '故障维修';
                                break;
                        }
                        $(td).text(tem);
                        break;
                    case 'maintenanceTime':
                        $(td).empty();
                        $(td).text(getDate(item['maintenanceTime']).datetime());
                        break;
                    case 'image':
                        $(td).empty();
                        if (!isNull(item['image'])) {
                            var img = createElement('img', td);
                            $(img).addClass('img-preview');
                            var fileName = prefix + item['image'].substring(item['image'].lastIndexOf("/") + 1, item['image'].lastIndexOf(".")) + suffix;
                            $(img).attr('src', fileUrl + item['image']);
                        }
                        break;
                    case 'opera':
                        var edit = createElement('a', td);
                        $(edit).addClass('font-p24');
                        $(edit).attr('href', '##');
                        $(edit).click(function () {
                            editInfo(item['id']);
                        });
                        var del = createElement('a', td);
                        $(del).addClass('font-p24').addClass('delete-option-btn').addClass('ml-2');
                        $(del).attr('href', '##');
                        $(del).click(function () {
                            deleteInfo(item['id']);
                        });
                        var editIcon = createElement('i', edit);
                        $(editIcon).addClass('iconfont').addClass('icon-bianji-');
                        var delIcon = createElement('i', del);
                        $(delIcon).addClass('iconfont').addClass('icon-shanchuicon');
                        break;
                }
            })
            $('.more-tooltip').tooltip();
            window.parent.changeIframeH();
        }
        /*  let str = '';
          for (let i = 1; i < data.length + 1; i++) {
              let result = data[i - 1];
              str += '<tr id=tr_' + i + '>' +
                  '<td>' + i + '</td>' +
                  '<td>' + result.ename + '</td>' +
                  '<td>' + result.name + '</td>' +
                  '<td>' + result.sn + '</td>' +
                  '<td>' + result.content + '</td>' +
                  '<td>' + getDate(result.maintenanceTime).datetime() + '</td>' +
                  '<td><img class="img-preview" src="' + fileUrl + result.image + '" alt=""></td>';
              if (deviceProcMaintenanceOpera) {
                  str += '<td>' +
                      '<a class="font-p24" href="##" onclick="editInfo(' + result.id + ')"><i class="iconfont icon-bianji-"></i></a>' +
                      '<a class="font-p24 delete-option-btn ml-2" href="##" onclick="deleteInfo(' + result.id + ')"><i class="iconfont icon-shanchuicon"></i></a>' +
                      '</td>';
              }
              str +=
                  '</tr>';
          }
          $("#maintenance_List tbody").append(str);*/
        hideLoading();
        // set_paging2(data.length, $("#maintenance_List tbody"));
    })
}


function generateReports() {
    window.location.href = "../maintenance/getInfoListExcel?dateTime=" + $('#searchTimeBegin').val()+"&token="+sessionStorage.getItem("token");
}